<template>
  <Layout>
    <div class="add-activity-container">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        当前位置：<router-link to="/home" class="breadcrumb-link">首页</router-link> > <span class="breadcrumb-current">编辑志愿项目</span>
      </div>

      <div class="page-header">
        <h2 class="page-title">编辑志愿项目</h2>
        <div class="title-divider"></div>
        <p class="page-desc">请修改以下信息编辑志愿服务项目</p>
      </div>
      
      <el-form :model="activityForm" :rules="rules" ref="activityFormRef" label-width="140px" class="activity-form">
        <div class="form-section">
          <div class="section-header">
            <div class="section-icon">
              <el-icon><InfoFilled /></el-icon>
            </div>
            <h3 class="section-title">基本信息</h3>
          </div>
          <el-form-item label="活动名称" prop="activityName">
            <el-input v-model="activityForm.activityName" placeholder="请输入活动名称"></el-input>
          </el-form-item>

          <el-form-item label="服务类别" prop="serviceCategory">
            <el-select v-model="activityForm.serviceCategory" placeholder="请选择服务类别" class="full-width">
              <el-option label="社区服务" :value="1"></el-option>
              <el-option label="文化艺术" :value="2"></el-option>
              <el-option label="义务维修" :value="3"></el-option>
              <el-option label="环境保护" :value="4"></el-option>
              <el-option label="交通引导" :value="5"></el-option>
              <el-option label="禁毒宣传" :value="6"></el-option>
              <el-option label="其他" :value="7"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="活动类型" prop="activityType">
            <el-select v-model="activityForm.activityType" placeholder="请选择活动类型" class="full-width">
              <el-option label="党支部志愿活动" :value="1"></el-option>
              <el-option label="校内志愿活动" :value="2"></el-option>
              <el-option label="院级活动" :value="3"></el-option>
              <el-option label="校外活动" :value="4"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="报名范围" prop="registrationScope">
            <el-select v-model="activityForm.registrationScope" placeholder="请选择报名范围" class="full-width">
              <el-option label="公开招募" :value="1"></el-option>
              <el-option label="指定志愿组织招募" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </div>

        <div class="form-section">
          <div class="section-header">
            <div class="section-icon">
              <el-icon><Phone /></el-icon>
            </div>
            <h3 class="section-title">联系方式</h3>
          </div>
          <el-form-item label="活动发起人" prop="initiator">
            <el-input v-model="activityForm.initiator" placeholder="请输入活动发起人"></el-input>
          </el-form-item>

          <el-form-item label="活动联系人" prop="contactPerson">
            <el-input v-model="activityForm.contactPerson" placeholder="请输入活动联系人"></el-input>
          </el-form-item>

          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="activityForm.contactPhone" placeholder="请输入联系电话"></el-input>
          </el-form-item>

          <el-form-item label="活动地址" prop="address">
            <el-input v-model="activityForm.address" placeholder="请输入活动地址"></el-input>
          </el-form-item>
        </div>

        <div class="form-section">
          <div class="section-header">
            <div class="section-icon">
              <el-icon><Timer /></el-icon>
            </div>
            <h3 class="section-title">活动时间与人数</h3>
          </div>
          <el-form-item label="活动时间" required>
            <el-col :span="11">
              <el-form-item prop="startDate">
                <el-date-picker type="datetime" placeholder="开始时间" v-model="activityForm.startDate" style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-center">
              <span class="text-gray-500">至</span>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="endDate">
                <el-date-picker type="datetime" placeholder="结束时间" v-model="activityForm.endDate" style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label="招募人数" prop="recruitmentNumber">
            <el-input-number v-model="activityForm.recruitmentNumber" :min="1" class="full-width"></el-input-number>
          </el-form-item>
        </div>

        <div class="form-section">
          <div class="section-header">
            <div class="section-icon">
              <el-icon><Document /></el-icon>
            </div>
            <h3 class="section-title">活动详情</h3>
          </div>
          <el-form-item label="活动详情" prop="details">
            <el-input type="textarea" v-model="activityForm.details" rows="4" placeholder="请输入活动详情"></el-input>
          </el-form-item>

          <el-form-item label="报名信息" prop="registrationInfo">
            <el-input type="textarea" v-model="activityForm.registrationInfo" rows="4" placeholder="请输入报名信息"></el-input>
          </el-form-item>

          <el-form-item label="时长公示" prop="durationDisplay">
            <el-input v-model="activityForm.durationDisplay" placeholder="请输入时长公示信息"></el-input>
          </el-form-item>

          <el-form-item label="志愿者保障信息" prop="volunteerProtectionInfo">
            <el-input type="textarea" v-model="activityForm.volunteerProtectionInfo" rows="4" placeholder="请输入志愿者保障信息"></el-input>
          </el-form-item>
        </div>

        <div class="form-section">
          <div class="section-header">
            <div class="section-icon">
              <el-icon><Picture /></el-icon>
            </div>
            <h3 class="section-title">活动图片</h3>
          </div>
          <el-form-item label="活动图片" prop="activityPictureInfo">
            <el-upload
              class="upload-demo"
              action="http://localhost:9090/api/upload/image"
              :show-file-list="true"
              :on-success="handleSuccess"
              :on-error="handleError"
              :before-upload="beforeUpload"
              list-type="picture"
            >
              <el-button type="primary">点击上传</el-button>
              <div class="upload-tip">支持jpg、png格式，大小不超过2MB</div>
            </el-upload>
            <div class="image-preview" v-if="activityForm.activityPictureInfo">
              <el-image 
                :src="activityForm.activityPictureInfo"
                fit="cover"
                class="preview-image"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
          </el-form-item>
        </div>

        <el-form-item class="form-buttons">
          <el-button type="primary" size="large" @click="submitForm" :loading="loading">{{ loading ? '更新中...' : '更新活动' }}</el-button>
          <el-button size="large" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </Layout>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, InfoFilled, Phone, Timer, Document, Picture } from '@element-plus/icons-vue';
import Layout from '@/components/Layout.vue';
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();
const activityFormRef = ref(null);
const loading = ref(false);

const activityForm = reactive({
  activityName: '',
  organizationId: '',
  serviceCategory: '',
  activityStatus: 1,
  activityType: '',
  registrationScope: '',
  initiator: '',
  contactPerson: '',
  contactPhone: '',
  address: '',
  details: '',
  registrationInfo: '',
  durationDisplay: '',
  volunteerProtectionInfo: '',
  startDate: '',
  endDate: '',
  activityPictureInfo: '',
  recruitmentNumber: 1,
  registeredNumber: 0
});

const rules = {
  activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  serviceCategory: [{ required: true, message: '请选择服务类别', trigger: 'change' }],
  activityType: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
  registrationScope: [{ required: true, message: '请选择报名范围', trigger: 'change' }],
  initiator: [{ required: true, message: '请输入活动发起人', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入活动联系人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入活动地址', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  recruitmentNumber: [{ required: true, message: '请输入招募人数', trigger: 'blur' }],
  details: [{ required: true, message: '请输入活动详情', trigger: 'blur' }],
  registrationInfo: [{ required: true, message: '请输入报名信息', trigger: 'blur' }],
  durationDisplay: [{ required: true, message: '请输入时长公示信息', trigger: 'blur' }],
  volunteerProtectionInfo: [{ required: true, message: '请输入志愿者保障信息', trigger: 'blur' }],
  activityPictureInfo: [{ required: true, message: '请上传活动图片', trigger: 'change' }]
};

onMounted(async () => {
  const activityId = route.params.activityId;
  if (activityId) {
    try {
      const response = await axios.get(`http://localhost:9090/activities/${activityId}`);
      if (response && response.data) {
        Object.assign(activityForm, response.data);
        // 转换服务类别、活动类型和报名范围为数字类型
        activityForm.serviceCategory = parseInt(activityForm.serviceCategory);
        activityForm.activityType = parseInt(activityForm.activityType);
        activityForm.registrationScope = parseInt(activityForm.registrationScope);
        // 转换日期字符串为Date对象
        activityForm.startDate = new Date(activityForm.startDate);
        activityForm.endDate = new Date(activityForm.endDate);
      } else {
        ElMessage.error('获取活动信息失败');
      }
    } catch (error) {
      ElMessage.error('获取活动信息失败');
    }
  } else {
    ElMessage.error('没有获取到活动ID');
  }
});

const submitForm = async () => {
  if (!activityFormRef.value) return;
  
  try {
    loading.value = true;
    await activityFormRef.value.validate();
    
    // 验证时间
    if (activityForm.endDate <= activityForm.startDate) {
      ElMessage.error('结束时间必须晚于开始时间');
      return;
    }

    const response = await axios.post('http://localhost:9090/activities/update', activityForm);
    console.log(response);
    
    if(response) {
      ElMessage.success('活动更新成功');
      router.push('/volunteer-project');
    } else {
      ElMessage.error(response.data?.message || '更新失败，请稍后重试');
    }
  } catch (error) {
    if (error.name === 'ValidationError') {
      ElMessage.error('请填写所有必填项');
    } else {
      console.log(error);
      ElMessage.error('更新失败：' + (error.response?.data?.message || error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  if (!activityFormRef.value) return;
  activityFormRef.value.resetFields();
};

// 上传前检查文件格式和大小
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件！');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！');
    return false;
  }

  return true;
};

// 处理上传成功
const handleSuccess = (response) => {
  ElMessage.success('上传成功！');
  console.log(response);
  activityForm.activityPictureInfo = "http://localhost:9090/api/upload/uploads/" + response;
};

// 处理上传失败
const handleError = (error) => {
  console.error('上传失败:', error);
  ElMessage.error('上传失败，请重试！');
};
</script>

<style scoped>
.add-activity-container {
  max-width: 1200px;
  margin: 20px auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
}

/* 面包屑导航样式 */
.breadcrumb {
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
}

.breadcrumb-link {
  color: #dd2b2b;
  text-decoration: none;
}

.breadcrumb-link:hover {
  color: #66b1ff;
}

.breadcrumb-current {
  color: #dd2b2b;
}

.page-header {
  text-align: center;
  margin-bottom: 60px;
  padding: 30px 0;
  background: linear-gradient(135deg, #fff6f6 0%, #fff 100%);
  border-radius: 16px;
}

.page-title {
  font-size: 36px;
  color: #1a1a1a;
  margin-bottom: 15px;
  font-weight: 700;
  background: linear-gradient(45deg, #FF4B4B, #FF0000);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}

.title-divider {
  width: 80px;
  height: 4px;
  background: linear-gradient(90deg, #FF4B4B, #FF0000);
  margin: 20px auto;
  border-radius: 2px;
}

.page-desc {
  color: #666;
  font-size: 16px;
  line-height: 1.6;
}

.form-section {
  margin-bottom: 40px;
  padding: 35px;
  background: #f8fafc;
  border-radius: 16px;
  border: 1px solid #eef2f7;
  transition: all 0.3s ease;
}

.form-section:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 2px solid rgba(255, 75, 75, 0.1);
}

.section-icon {
  width: 40px;
  height: 40px;
  background: linear-gradient(45deg, #FF4B4B, #FF0000);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  box-shadow: 0 4px 12px rgba(255, 75, 75, 0.2);
}

.section-icon .el-icon {
  font-size: 20px;
  color: white;
}

.section-title {
  font-size: 22px;
  color: #1a1a1a;
  font-weight: 600;
  margin: 0;
}

.full-width {
  width: 100%;
}

.upload-tip {
  font-size: 14px;
  color: #909399;
  margin-top: 0px;
  margin-left: 10px;
}

.form-buttons {
  text-align: center;
  margin-top: 60px;
}

.form-buttons .el-button {
  padding: 15px 60px;
  font-size: 16px;
  border-radius: 30px;
  transition: all 0.3s ease;
}

.form-buttons .el-button--primary {
  background: linear-gradient(45deg, #FF4B4B, #FF0000);
  border: none;
}

.form-buttons .el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 15px rgba(255, 75, 75, 0.3);
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #1a1a1a;
  font-size: 15px;
}

:deep(.el-input__inner) {
  height: 46px;
  line-height: 46px;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

:deep(.el-input__inner:focus) {
  border-color: #FF4B4B;
  box-shadow: 0 0 0 2px rgba(255, 75, 75, 0.1);
}

:deep(.el-textarea__inner) {
  min-height: 120px !important;
  border-radius: 12px;
  padding: 15px;
  line-height: 1.6;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  border-radius: 12px;
}

.image-preview {
  margin-left: 20px;
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.image-preview:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.preview-image {
  width: 300px;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
  border: 2px solid #eef2f7;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  border-radius: 8px;
}

.image-slot .el-icon {
  font-size: 32px;
  opacity: 0.5;
}
</style>